# -*- coding: utf-8 -*-

"""
@Datetime: 2018/11/6
@Author: Zhang Yafei
"""
import pika
import subprocess

credentials = pika.PlainCredentials('admin','admin')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.137.3',5672,'/',credentials))
channel = connection.channel()

channel.queue_declare(queue='rpc_queue')


def process_cmd(cmd):
    res = subprocess.Popen(cmd, shell=True,
                           stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stdin=subprocess.PIPE,
                           )
    err = res.stderr.read()
    if err:
        cmd_res = err
    else:
        cmd_res = res.stdout.read()
    # print(cmd_res.decode('gbk'))
    return cmd_res


def on_request(ch, method, props, body):
    cmd = body.decode('utf-8')

    print('>>:',cmd)
    response = process_cmd(cmd)

    ch.basic_publish(exchange='',
                     routing_key=props.reply_to,
                     properties=pika.BasicProperties(correlation_id= \
                                                         props.correlation_id),
                     body=response)
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue='rpc_queue')

print(" [x] Awaiting RPC requests")
channel.start_consuming()